package com.lxmes.gs.service.impl;

import java.util.Arrays;
import java.util.List;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.lxmes.gs.domain.MyTask;
import com.lxmes.gs.domain.WorkingHoursSubmission;
import com.lxmes.gs.service.IMyTaskService;
import com.lxmes.gs.service.IWorkingHoursSubmissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.lxmes.common.utils.StringUtils;
import com.lxmes.common.utils.bean.BeanValidators;
import com.lxmes.common.exception.ServiceException;
import javax.validation.Validator;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lxmes.gs.mapper.TaskProgressMapper;
import com.lxmes.gs.domain.TaskProgress;
import com.lxmes.gs.service.ITaskProgressService;

/**
 * 任务进度Service业务层处理
 * 
 * @author wdf
 * @date 2023-04-24
 */
@Service
public class TaskProgressServiceImpl extends ServiceImpl<TaskProgressMapper,TaskProgress> implements ITaskProgressService{
    
    @Autowired
    private TaskProgressMapper taskProgressMapper;
    @Autowired
    protected Validator validator;
    @Autowired
    private IMyTaskService myTaskService;
    @Autowired
    private IWorkingHoursSubmissionService workingHoursSubmissionService;
    /**
     * 查询任务进度
     * 
     * @param id 任务进度主键
     * @return 任务进度
     */
    @Override
    public TaskProgress selectTaskProgressById(Long id){
        return taskProgressMapper.selectById(id);
    }

    /**
     * 查询任务进度列表
     * 
     * @param taskProgress 任务进度
     * @return 任务进度
     */
    @Override
    public List<TaskProgress> selectTaskProgressList(TaskProgress taskProgress){
        return taskProgressMapper.selectList(Wrappers.lambdaQuery(taskProgress));
    }

    /**
     * 新增任务进度
     * 
     * @param taskProgress 任务进度
     * @return 结果
     */
    @Override
    public int insertTaskProgress(TaskProgress taskProgress){
        setTaskStatus(taskProgress);
        return taskProgressMapper.insert(taskProgress);
    }

 

    private void setTaskStatus(TaskProgress taskProgress) {
        MyTask myTask = myTaskService.getOne(Wrappers.lambdaQuery(MyTask.class).eq(MyTask::getTaskCode, taskProgress.getTaskCode()));
        long between = DateUtil.between(taskProgress.getPlanStartTime(), myTask.getPlanEndTime(), DateUnit.MINUTE);
        WorkingHoursSubmission workingHoursSubmission = workingHoursSubmissionService.getOne(Wrappers.lambdaQuery(WorkingHoursSubmission.class).eq(WorkingHoursSubmission::getTaskCode, taskProgress.getTaskCode()));
        Double accumulatedWorkingHours;
        if (workingHoursSubmission == null) {
            accumulatedWorkingHours = 0D;
        } else {
            accumulatedWorkingHours = ObjectUtil.defaultIfNull(workingHoursSubmission.getAccumulatedWorkingHours(),0D);
        } 
        taskProgress.setTaskStatus(Convert.toStr(accumulatedWorkingHours /between));
    }

    /**
     * 修改任务进度
     * 
     * @param taskProgress 任务进度
     * @return 结果
     */
    @Override
    public int updateTaskProgress(TaskProgress taskProgress){
        return taskProgressMapper.updateById(taskProgress);
    }

    /**
     * 批量删除任务进度
     * 
     * @param ids 需要删除的任务进度主键
     * @return 结果
     */
    @Override
    public int deleteTaskProgressByIds(Long[] ids){
        return taskProgressMapper.deleteTaskProgressByIds(ids);
    }

    /**
     * 删除任务进度信息
     * 
     * @param id 任务进度主键
     * @return 结果
     */
    @Override
    public int deleteTaskProgressById(Long id){
        return taskProgressMapper.deleteById(id);
    }
    @Override
    public String imporIteminfo(List<TaskProgress> taskProgressList, boolean updateSupport) {
        if (StringUtils.isNull(taskProgressList) || taskProgressList.size() == 0)
        {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (TaskProgress taskProgress : taskProgressList)
        {
            try
            {
                BeanValidators.validateWithException(validator, taskProgress);
                this.insertTaskProgress(taskProgress);
                successNum++;
                successMsg.append("<br/>" + successNum + "数据导入成功");
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/> 数据导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public int auditTaskProgress(Long[] ids) {
        List<TaskProgress> taskProgresses = baseMapper.selectBatchIds(Arrays.asList(ids));
        for (TaskProgress taskProgress : taskProgresses) {
            setTaskStatus(taskProgress);
        }
        return 1;
    }
}
